"use strict";
const { Service } = require("egg");
const { Op } = require("sequelize");

class HomeService extends Service {
  async getIndexData() {
    let tv_count = await this.app.model.Teleplay.count({
      where: { show: true },
    });
    let movie_count = await this.app.model.Movie.count({
      where: { show: true },
    });
    let tv_list = await this.getTvList();
    let movie_list = await this.getMovieList();
    let dat = {
      tv_count,
      tv_list,
      movie_count,
      movie_list
    };
    return { data: dat };
  }
  async getTvList() {
    let tmp = [];
    let class_list = await this.app.model.TeleplayClass.findAll();
    for (let itm of class_list) {
      let count = await this.app.model.Teleplay.count({
        where: {
          show: true,
          classify: {
            [Op.like]: `%${itm.name}%`,
          },
        },
      });
      tmp.push({
        classify: itm.name,
        count,
        idx: itm.idx == null ? 99 : Number(itm.idx),
      });
    }
    let list_count = 15;
    let list = tmp.sort((a, b) => b.count - a.count);
    if (tmp.length > list_count) {
      list.length = list_count;
    }
    let ret = list.sort((a, b) => a.idx - b.idx);
    return ret;
  }
  async getMovieList() {
    let tmp = [];
    let class_list = await this.app.model.MovieClass.findAll();
    for (let itm of class_list) {
      let count = await this.app.model.Movie.count({
        where: {
          show: true,
          classify: {
            [Op.like]: `%${itm.name}%`,
          },
        },
      });
      tmp.push({
        classify: itm.name,
        count,
        idx: itm.idx == null ? 99 : Number(itm.idx),
      });
    }
    let list_count = 15;
    let list = tmp.sort((a, b) => b.count - a.count);
    if (tmp.length > list_count) {
      list.length = list_count;
    }
    let ret = list.sort((a, b) => a.idx - b.idx);
    return ret;
  }
}

module.exports = HomeService;
